<template>
  <div>
    <Form
      oneitem="商品搜索："
      :select-show="false"
      :total-count="totalCount"
      :total-page="totalPage"
      :search-list="skuList"
      :config-click-show="true"
      :page-index="pageIndex"
      button-text="导入数据"
      @searchResultFn="searchResultFn"
      @newCreateFn="newCreateFn"
      @changeList="changeList"
      @configCilck="configCilck"
    >
      <template #tableForm>
        <el-table-column label="序号" width="80" type="index" :index="indexMethod" />
        <el-table-column prop="skuName" label="商品名称" />
        <el-table-column prop="skuImage" label="商品图片">
          <template slot-scope="scope">
            <img :src="scope.row.skuImage" alt="" class="skuimg">
          </template>
        </el-table-column>
        <el-table-column prop="brandName" label="品牌" />
        <el-table-column prop="unit" label="规格" />
        <el-table-column prop="price" label="商品价格" />
        <el-table-column prop="skuClass.className" label="商品类型" />
        <el-table-column prop="createTime" label="创建日期" />
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="edit(scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </template>
    </Form>
    <!-- 新增商品 -->
    <el-dialog :title="skuForm.skuId?'修改商品':'新增商品'" :visible.sync="dialogVisible" width="630px" @open="openDialog" @closed="closeDialog">
      <el-form ref="skuForm" :model="skuForm" status-icon label-width="140px" :rules="skuFormRules">
        <el-form-item label="商品名称：" prop="skuName">
          <el-input v-model="skuForm.skuName" type="text" placeholder="请输入" maxlength="15" show-word-limit />
        </el-form-item>
        <el-form-item label="品牌：" prop="brandName">
          <el-input
            v-model="skuForm.brandName"
            type="text"
            placeholder="请输入"
            maxlength="10"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="商品价格(元)：" prop="price">
          <el-input-number v-model="skuForm.price" controls-position="right" :precision="2" :step="0.5" :min="0.50" :max="999.99" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="商品类型：" prop="classId">
          <el-select v-model="skuForm.classId" placeholder="请输入">
            <el-option v-for="item in classTypeList" :key="item.classId" :label="item.className" :value="item.classId" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格：" prop="unit">
          <el-input
            v-model="skuForm.unit"
            type="text"
            placeholder="请输入 "
            maxlength="15"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="商品图片：" prop="skuImage">
          <!-- 图片上传组件 -->
          <UploadImg v-model="skuForm.skuImage" />
          <div style="font-size: 14px;color: #bac0cd; margin-top: 7px;">支持扩展名：jpg、png，文件不得大于100kb</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="dialogVisible=false">取 消</el-button>
        <el-button id="buttom1" type="primary" @click="creatFn">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="数据导入" :visible.sync="uploadVisible" width="483px">
      <div class="upload">
        <el-upload
          class="upload-demo"
          action="/"
          :before-upload="beforeAvatarUpload"
          :limit="1"
          :http-request="uploadFn"
        >
          <div class="upload-top"><span>标题：</span><el-button class="upload-btn">上传文件</el-button></div>
          <div slot="tip" class="el-upload__tip">支持扩展名：xls、xlsx，文件不得大于1M</div>
        </el-upload>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button id="buttom2" @click="uploadVisible=false">取 消</el-button>
        <el-button id="buttom1" type="primary" @click="addUpload">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Form from '@/components/form/index.vue'
import { skuSearchList, skuClass, addSku, editSkuInfo, uploadSku } from '@/api'
export default {
  components: { Form },
  data() {
    return {
      skuList: [],
      pageIndex: 1,
      totalPage: null,
      totalCount: null,
      dialogVisible: false,
      skuForm: {
        skuName: null,
        skuImage:	null,
        price:	undefined,
        classId:	null,
        unit:	null,
        brandName: null
      },
      skuFormRules: {
        skuName: [{ required: true, message: '请输入' }],
        skuImage:	[{ required: true, message: '请输入' }],
        price:	[{ required: true, message: '请输入' }],
        classId:	[{ required: true, message: '请输入' }],
        unit:	[{ required: true, message: '请输入' }],
        brandName: [{ required: true, message: '请输入' }]
      },
      classTypeList: [],
      uploadVisible: false,
      formData: null
    }
  },
  created() {
    this.skuSearch(this.pageIndex)
  },
  methods: {
    async skuSearch(pageIndex, skuName, classId) {
      const res = await skuSearchList({
        pageIndex,
        pageSize: 10,
        skuName,
        classId
      })
      res.data.currentPageRecords.forEach(item => {
        item.price = item.price / 100
        item.createTime = item.createTime.replace(/-/g, '.').replace('T', ' ')
      })
      this.skuList = res.data.currentPageRecords
      this.totalPage = res.data.totalPage
      this.totalCount = res.data.totalCount
    },
    indexMethod(index) {
      return this.pageIndex === 1 ? index + 1 : Number(`${this.pageIndex - 1}${index}`) + 1
    },
    searchResultFn(val) {
      this.skuSearch(1, val.taskCode)
    },
    newCreateFn() {
      this.dialogVisible = true
    },
    changeList(page) {
      this.pageIndex = page
      this.skuSearch(page)
    },
    getUrl(url) {
      this.skuForm.skuImage = url
    },
    async openDialog() {
      const res = await skuClass({ pageIndex: 1, pageSize: 1000 })
      this.classTypeList = res.data.currentPageRecords
    },
    closeDialog() {
      this.skuForm = {
        skuName: null,
        skuImage:	null,
        price:	undefined,
        classId:	null,
        unit:	null,
        brandName: null
      }
      this.$refs.skuForm.resetFields()
    },
    // 确定添加
    creatFn() {
      this.$refs.skuForm.validate(async(valid) => {
        if (!valid) return
        if (this.skuForm.skuId) {
          await editSkuInfo(this.skuForm.skuId, this.skuForm).then(() => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
          }).catch(res => {
            this.$message({
              type: 'warning',
              message: res.response.data
            })
          })
        } else {
          await addSku(this.skuForm).then(() => {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
          }).catch(res => {
            this.$message({
              type: 'warning',
              message: res.response.data
            })
          })
        }
      })
      this.dialogVisible = false
    },
    // 修改
    edit(row) {
      this.dialogVisible = true
      this.skuForm = row
      this.skuForm = {
        skuName: row.skuName,
        skuImage:	row.skuImage,
        price:	row.price,
        classId:	row.classId,
        unit:	row.unit,
        brandName: row.brandName,
        skuId: row.skuId
      }
    },
    // 上传
    configCilck() {
      this.uploadVisible = true
    },
    beforeAvatarUpload(file) {
      console.log(file)
      const fileList = [
        '.xlsx',
        '.xls'
      ]
      const isJPG = fileList.includes(file.name
        .substr(file.name.lastIndexOf('.'))
        .toLowerCase())// 文件后缀名字
      const isLt2M = file.size / 1024 / 1024 < 1

      if (!isJPG) {
        this.$message.error('请上传正确格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 1M!')
      }
      return isJPG && isLt2M
    },
    async uploadFn(obj) {
      const formData = new FormData()
      formData.append(
        'fileName',
        obj.file
      )
      // console.log(formData)
      this.formData = formData
    },
    async addUpload() {
      await uploadSku(this.formData).then(() => {
        this.$message.success('上传成功')
        this.uploadVisible = false
      }).catch(res => {
        this.$message.warning(res.response.data)
      })
      // console.log(res)
    }
  }
}
</script>

<style lang="scss" scoped>
.skuimg {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #f3f6fb;
  border: 1px solid #f3f6fb;
}
.upload{
  width: 100%;
  text-align: center;
}
.el-upload__tip{
  margin-top: 7px;
  font-size: 14px;
  margin-left: 100px;
  color: #bac0cd;
}
.upload-btn{
    display: flex;
    justify-content: center;
    align-items: center;
    min-width: 80px;
    height: 36px;
    padding: 0;
    background-color: #5f84ff;
    border: none;
    width: 221px;
    color: #fff;
}
.upload-top{
  display: flex;
  font-size: 14px;
  align-items: center;
  span{
    padding-right: 12px;
  }
}
</style>
